const Router = require('koa-Router')
let router = new Router()
var Mock = require('mockjs');
//安防管理
var data = Mock.mock({
    'protectdata|20': [{
        'stuNo|+1': 1,
        "stuName": "@cname",
        image: "@image(80x80,@color)",
        "bourn|1": ['2111A', '2007A', '2008A', '2110A', '2112A', '2009A'],
        "type|1": [true, false]
    }]
})

router.get('/api/list', ctx => {
    ctx.body = {
        code: 200,
        msg: '返回信息1',
        data: data.protectdata
    }
})
//删除
router.delete('/api/delprotect', ctx => {
    const { stuNo } = ctx.query
    //如果没有传递id返回缺少id
    if (!stuNo) {
        ctx.body = {
            code: 400,
            msg: '缺少删除的ID'
        }
        return
    }
    const ids = stuNo.includes(',') ? stuNo.split(',').map((id) => id.trim()) : [stuNo.trim()]
    const idsSet = new Set(ids)
    data.protectdata = data.protectdata.filter(item => !idsSet.has(item.stuNo.toString())) // 将 item.stuNo 转换为字符串进行
    ctx.body = {
        code: 200,
        msg: "删除成功",
        data: data.protectdata
    }
})
//新增
router.post('/api/addprotect', ctx => {
    const { stuName, image, bourn, type } = ctx.request.body
    let obj = {
        stuNo: +new Date(),
        stuName,
        image,
        bourn,
        type
    }
    data.protectdata.unshift(obj)
    ctx.body = {
        code: 200,
        msg: '新增成功',
        data: data.protectdata
    }
})
//编辑
router.post('/api/editprotect', ctx => {
    const { stuNo, stuName, image, bourn, type } = ctx.request.body
    let items = data.protectdata.find((item) => item.stuNo == stuNo)
    items.stuName = stuName
    items.image = image
    items.bourn = bourn
    items.type = type
    ctx.body = {
        code: 200,
        msg: '修改成功',
        data: data.protectdata
    }
})
//搜索
router.get('/api/protect/sou', ctx => {
    const { stuName } = ctx.query
    console.log(stuName);

    if (!stuName) {
        ctx.body = {
            code: 200,
            msg: '查询成功',
            data: data.protectdata
        }
        return
    }

    let shuju = data.protectdata.filter((item) => item.stuName.includes(stuName))

    ctx.body = {
        code: 200,
        msg: '查询成功',
        data: shuju
    }
})

module.exports = router